package com.donger.upms.biz.controller;


import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.donger.common.log.annotation.Log;
import com.donger.common.core.exception.BizException;
import com.donger.common.core.utils.Res;
import com.donger.common.core.utils.Result;
import com.donger.common.security.service.UserDetail;
import com.donger.upms.api.dto.UserForm;
import com.donger.upms.api.entity.SysUser;
import com.donger.upms.api.entity.UserDto;
import com.donger.upms.api.entity.UserInfo;
import com.donger.upms.api.service.ISysUserService;
import com.donger.upms.biz.utils.CaptchaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * <p>
 * 系统用户 前端控制器 基本完成
 * </p>
 *
 * @author xyx
 * @since 2019-01-12
 * 用户表增加 别名 user
 */
@AllArgsConstructor
@RestController
@RequestMapping("/sys/user")
@Api(tags = "系统用户管理")
public class SysUserController extends BaseController {

    private static final String MODULE_NAME = "系统用户管理";
    private static final Long SUPER_ADMIN = 1L;

    private final ISysUserService sysUserService;

    private final PasswordEncoder passwordEncoder;

    private final CaptchaService captchaService;

    /**
     * 所有用户列表
     */
    @GetMapping("/list")
    @ApiOperation(notes = "分页查询用户", value = "")
    public Result list(Page<SysUser> page, SysUser sysUser) {
        return Res.ok(sysUserService.getUserWithRolePage(page, Wrappers.query(sysUser)
                .eq("user.del_flag", 0)
                .eq(StrUtil.isNotBlank(sysUser.getUsername()), "user.username", sysUser.getUsername()
                )));
    }

    /**
     * 获取登录的用户信息  用户登陆
     */
    @GetMapping("/info")
    public Result<UserInfo> info() {
        Long currentUserId = getCurrentUserId();
        SysUser user = sysUserService.getById(currentUserId);
        if (currentUserId == null) {
            throw new BizException("获取用户信息失败，请重新登录！");
        }
        return Res.ok(sysUserService.findUserInfo(user));
    }


    /**
     * 用户信息
     */
    @GetMapping("/info/{userId}")
    public Result<UserInfo> info(@PathVariable("userId") Long userId) {
        SysUser user = sysUserService.getById(userId);
        //获取用户所属的角色列表
        UserInfo userInfo = sysUserService.findUserInfo(user);
        return Res.ok(userInfo);
    }

    /**
     * 保存用户
     */
    @Log(value = "保存用户信息", moduleName = MODULE_NAME)
    @PostMapping("/save")
    public Result<Boolean> save(@RequestBody UserDto user) {
        return Res.ok(sysUserService.saveUser(user));
    }

    /**
     * 修改用户
     */
    @Log(value = "修改用户信息", moduleName = MODULE_NAME)
    @PostMapping("/update")
    public Result<Boolean> update(@RequestBody UserDto user) {
        return Res.ok(sysUserService.updateUserById(user));
    }

    /**
     * 删除用户
     */
    @Log(value = "删除用户信息", moduleName = MODULE_NAME)
    @GetMapping("/delete/{userId}")
    public Result<Boolean> delete(@PathVariable("userId") Long userId) {
        if (userId.equals(SUPER_ADMIN)) {
            return Res.error("不能删除管理员");
        }
        if (userId.equals(getCurrentUserId())) {
            return Res.error("当前用户不能删除");
        }
        return Res.ok(sysUserService.deleteUserById(userId));
    }


    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response, String uuid) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //获取图片验证码
        BufferedImage image = captchaService.getCaptcha(uuid);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IoUtil.close(out);
    }

    @PostMapping("/edit")
    public Result edit(@RequestBody UserForm userForm) {
        UserDetail userDetail = getCurrentUser();
        SysUser temp = new SysUser();

        if (StrUtil.isNotBlank(userForm.getPassword()) && StrUtil.isNotBlank(userForm.getNewpassword1())) {
            String password = passwordEncoder.encode(userForm.getPassword());
            String newPassword = passwordEncoder.encode(userForm.getNewpassword1());
            //更新密码
            boolean flag = sysUserService.updatePassword(getCurrentUserId(), password, newPassword);
            if (!flag) {
                return Res.error("原密码错误，修改失败");
            }
        }
        temp.setUserId(userDetail.getUserId());
        temp.setAvatar(userForm.getAvatar());
        temp.setPhone(userForm.getPhone());
        sysUserService.update(temp, new LambdaUpdateWrapper<SysUser>().eq(SysUser::getUserId, userDetail.getUserId()));
        return Res.ok();
    }

}

